from flask import Blueprint, current_app, request
from flask_bcrypt import generate_password_hash, check_password_hash
from flask_restful import Resource
import sqlite3
from . import api_rest

class Check_name(Resource):
    def get(self,username):
        # print(username)
        order = "select count(*) from ADMINISTRATOR where USERNAME='" + username + "'"
        # print(order)
        conn = sqlite3.connect('backend/outbreak-management-system.db')
        c = conn.cursor()
        c.execute(order)
        cursor = c.fetchall()
        conn.close()
        return {'count':cursor[0][0]}


class Register_admin(Resource):
    def post(self):
        body = request.get_json()
        password = body['password']
        password_hash = generate_password_hash(password).decode('utf8')
        id = body['id']
        username = body['username']
        name = body['name']
        corridornumber = body['corridornumber']
        telephone = body['telephone']
        order = "insert into ADMINISTRATOR values ('"+ id + "','" + username + "','" + password_hash + "','" + name + "'," + str(corridornumber) + ",'" + telephone +"')"
        print(order)
        conn = sqlite3.connect('backend/outbreak-management-system.db')
        c = conn.cursor()
        c.execute(order)
        conn.commit()
        conn.close()
        return {'name':name}, 200

class Register_properietor(Resource):
    def post(self):
        body = request.get_json()
        password = body['password']
        password_hash = generate_password_hash(password).decode('utf8')
        id = body['id']
        username = body['username']
        name = body['name']
        age = body['age']
        sex = body['sex']
        roomnumber = body['roomnumber']
        corridornumber = body['corridornumber']
        telephone = body['telephone']
        
        conn = sqlite3.connect('backend/outbreak-management-system.db')
        c = conn.cursor()
        # 查询adminid
        order = "select ID from ADMINISTRATOR where CORRIDORNUMBER='" + corridornumber +"'"
        print(order)
        c.execute(order)
        cursor = c.fetchall()
        adminid = cursor[0][0]

        order = "insert into PROPRIETOR values ('"+ id + "','" + username + "','" + password_hash + "','" + name + "'," + str(age) + "," + str(sex) + ",'" + roomnumber + "','" + corridornumber + "','" + telephone + "','" + adminid +"')"
        print(order)
        
        c.execute(order)
        conn.commit()
        conn.close()
        return {'name':name}, 200

api_rest.add_resource(Register_admin, '/register/admin')
api_rest.add_resource(Register_properietor, '/register/properietor')
api_rest.add_resource(Check_name, '/username/<username>')